import {reqCate,reqCateGoods} from '../../request/api'

//初始状态
const initState={
    goodsCate: [],//分类
    goods: [],//商品
    fid: '1'
};

// actionType
const TYPES={
CATE_CHANGE_GOODSCATE:'CATE_CHANGE_GOODSCATE',
CATE_CHANGE_GOODS:'CATE_CHANGE_GOODS',
CATE_CHANGE_FID:'CATE_CHANGE_FID'
};

// reducer
const reducer=(state=initState,action)=>{
    switch (action.type){
        case TYPES.CATE_CHANGE_GOODSCATE:
            return {
                ...state,
                goodsCate:action.goodsCate
            }
            case TYPES.CATE_CHANGE_GOODS:
                return {
                    ...state,
                    goods:action.goods
                }
                case TYPES.CATE_CHANGE_FID:
                return {
                    ...state,
                    fid:action.fid
                }
        default:
            return state;
    }
};

// actionCreators
export const actions={
    // 修改商品分类数据
changeGoodsCate:(goodsCate)=>({type:TYPES.CATE_CHANGE_GOODSCATE,goodsCate}),
// 请求商品分类数据
requestGoodsCate:()=>{
    return (dispatch,getState)=>{
        // 判断状态层是否有数据，没有数据才请求
        let goodsCate = getGoodsCate(getState())
        if (goodsCate.length > 0) {
            return;
        }
        reqCate().then(res=>{
            if(res.data.code==200){
                dispatch(actions.changeGoodsCate(res.data.list))
            }
        })
    }
},
// 修改商品
changeGoods:(goods)=>({type:TYPES.CATE_CHANGE_GOODS,goods}),
// 请求商品
requestGoods:()=>{
    return (dispatch,getState)=>{
        let fid=getFid(getState());
        reqCateGoods({fid}).then(res=>{
            if(res.data.code==200){
                dispatch(actions.changeGoods(res.data.list))
            }
        })
    }
},
// 修改fid
changeFid:(fid)=>{
        // console.log(fid);
        return (dispatch,getState)=>{
            dispatch({type:TYPES.CATE_CHANGE_FID,fid});
            dispatch(actions.requestGoods())
        }
       
    }
};
// selectors 导出数据
export const getGoodsCate=state=>state.cate.goodsCate;
export const getGoods=state=>state.cate.goods;
export const getFid=state=>state.cate.fid;

export default reducer;